<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="课程分类" prop="categoryId">
        <el-select v-model="queryParams.categoryId" placeholder="请选择是否热门" clearable size="small">
          <el-option
            v-for="dict in categoryOptions"
            :key="dict.categoryId"
            :label="dict.categoryName"
            :value="dict.categoryId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="课程名称" prop="courseName">
        <el-input
          v-model="queryParams.courseName"
          placeholder="请输入课程名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否热门" prop="courseHot">
        <el-select v-model="queryParams.courseHot" placeholder="请选择是否热门" clearable size="small">
          <el-option
            v-for="dict in hotStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否最新" prop="courseNew">
        <el-select v-model="queryParams.courseNew" placeholder="请输入是否最新" clearable size="small">
          <el-option
            v-for="dict in newStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否支持试看" prop="courseTry">
        <el-select v-model="queryParams.courseTry" placeholder="请输入是否支持试看" clearable size="small">
          <el-option
            v-for="dict in tryStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="auditStatus">
        <el-select v-model="queryParams.auditStatus" placeholder="请选择审核状态" clearable size="small">
          <el-option
            v-for="dict in auditStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="上架状态" prop="sellStatus">
        <el-select v-model="queryParams.sellStatus" placeholder="请选择上架状态" clearable size="small">
          <el-option
            v-for="dict in sellStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['knowledge:course:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['knowledge:course:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['knowledge:course:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['knowledge:course:export']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="courseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="courseId" />
      <el-table-column label="课程分类" align="center" prop="categoryId" :formatter="categoryFormat"/>
      <el-table-column label="课程名称" align="center" prop="courseName" :show-overflow-tooltip='true' />
      <el-table-column label="章节数" align="center" prop="chaptersNum" />
      <el-table-column label="描述" align="center" prop="courseDescription" :show-overflow-tooltip='true' />
      <el-table-column label="封面图" align="center" prop="courseImgs" >
        <template slot-scope="scope">
          　　　　<el-image :src="scope.row.courseImgs" width="40" height="40" class="head_pic"/>
    　　</template>
      </el-table-column>
      <el-table-column label="原价" align="center" prop="courseOldPrice" />
      <el-table-column label="现价" align="center" prop="coursePrice" />
      <el-table-column label="是否热门" align="center" prop="courseHot" :formatter="courseHotFormat"/>
      <el-table-column label="是否最新" align="center" prop="courseNew" :formatter="courseNewFormat"/>
      <el-table-column label="销量" align="center" prop="courseSales" />
      <el-table-column label="是否支持试看" align="center" prop="courseTry" :formatter="courseTryFormat"/>
      <el-table-column label="试看页数" align="center" prop="courseTryPages" />
      <el-table-column label="试看时长（秒）" align="center" prop="courseTryTimes" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="审核状态" align="center" prop="auditStatus" :formatter="auditStatusFormat" />
      <el-table-column label="上架状态" align="center" prop="sellStatus" :formatter="sellStatusFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['knowledge:course:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['knowledge:course:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改知识/课程对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="课程名称" prop="courseName">
              <el-input v-model="form.courseName" placeholder="请输入课程名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程分类" prop="categoryId">
              <el-select v-model="form.categoryId"  placeholder="请选择课程分类">
                <el-option
                  v-for="item in categoryOptions"
                  :key="item.categoryId"
                  :label="item.categoryName"
                  :value="item.categoryId"
                ></el-option>
              </el-select>

            <!--  <treeselect v-model="form.categoryId" :options="categoryOptions" :show-count="true" placeholder="请选择课程分类" />-->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="章节数" prop="chaptersNum">
              <el-input v-model="form.chaptersNum" placeholder="请输入章节数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="描述" prop="courseDescription">
              <el-input v-model="form.courseDescription" placeholder="请输入描述" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">

            <el-form-item label="审核状态">
              <el-radio-group v-model="form.auditStatus">
                <el-radio
                  v-for="dict in auditStatusOptions"
                  :key="dict.dictValue"
                  :label="parseInt(dict.dictValue)"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
              <el-col :span="12">
            <el-form-item label="原价" prop="courseOldPrice">
              <el-input v-model="form.courseOldPrice" placeholder="请输入原价" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="现价" prop="coursePrice">
              <el-input v-model="form.coursePrice" placeholder="请输入现价" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否热门" prop="courseHot">
              <el-radio-group v-model="form.courseHot">
                <el-radio
                  v-for="dict in hotStatusOptions"
                  :key="dict.dictValue"
                  :label="parseInt(dict.dictValue)"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否最新" prop="courseNew">
              <el-radio-group v-model="form.courseNew">
                <el-radio
                  v-for="dict in newStatusOptions"
                  :key="dict.dictValue"
                  :label="parseInt(dict.dictValue)"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销量" prop="courseSales">
              <el-input v-model="form.courseSales" placeholder="请输入销量" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否支持试看" prop="courseTry">
              <el-radio-group v-model="form.courseTry">
                <el-radio
                  v-for="dict in tryStatusOptions"
                  :key="dict.dictValue"
                  :label="parseInt(dict.dictValue)"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="试看页数" prop="courseTryPages">
              <el-input v-model="form.courseTryPages" placeholder="请输入试看页数" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="试看时长（秒）" prop="courseTryTimes">
              <el-input v-model="form.courseTryTimes" placeholder="请输入试看时长，单位为秒" />
            </el-form-item>
          </el-col>
          <el-col :span="12">

            <el-form-item label="上架状态">
              <el-radio-group v-model="form.sellStatus">
                <el-radio
                  v-for="dict in sellStatusOptions"
                  :key="dict.dictValue"
                  :label="parseInt(dict.dictValue)"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="封面图" prop="courseImgs">
              <el-upload :on-success="handleAvatarSuccess" :action="field101Action" :before-upload="beforeUpload" :limit="1" >
              <!--  <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>-->
                <el-image v-if="form.courseImgs" :src="form.courseImgs" class="avatar" style="width: 100px;height: 100px;"></el-image>
                <i v-else class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCourse, getCourse, delCourse, addCourse, updateCourse, exportCourse,getAllCategory,uploadAction } from "@/api/knowledge/course";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {uploadAvatar} from "@/api/system/user";
import store from "@/store";
export default {
  name: "Course",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 知识/课程表格数据
      courseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 审核状态：0待审核1审核通过2审核不通过字典
      auditStatusOptions: [],
      // 最热状态：0未上架1已上架字典
      hotStatusOptions: [],
      // 最新状态：0未上架1已上架字典
      newStatusOptions: [],
      // 试看状态：0未上架1已上架字典
      tryStatusOptions: [],
      // 上架状态：0未上架1已上架字典
      sellStatusOptions: [],
      //课程分类
      categoryOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: null,
        courseName: null,
        courseHot: null,
        courseNew: null,
        courseTry: null,
        auditStatus: null,
        sellStatus: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      field101Action: process.env.VUE_APP_BASE_API+'/common/upload',
      field101fileList: [],
    };
  },
  created() {
    this.getList();
    this.getAllCategory();
    this.getDicts("audit_status").then(response => {
      this.auditStatusOptions = response.data;
    });
    this.getDicts("sell_status").then(response => {
      this.sellStatusOptions = response.data;
    });
    this.getDicts("hot_status").then(response => {
      this.hotStatusOptions = response.data;
    });
    this.getDicts("new_status").then(response => {
      this.newStatusOptions = response.data;
    });
    this.getDicts("try_status").then(response => {
      this.tryStatusOptions = response.data;
    });
  },
  methods: {
    /** 查询知识/课程列表 */
    getList() {
      this.loading = true;
      listCourse(this.queryParams).then(response => {
        this.courseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getAllCategory() {
      getAllCategory().then(response => {
        this.categoryOptions = response;
      });
    },
    // 审核状态：0待审核1审核通过2审核不通过字典翻译
    auditStatusFormat(row, column) {
      return this.selectDictLabel(this.auditStatusOptions, row.auditStatus);
    },
    // 上架状态：0未上架1已上架字典翻译
    sellStatusFormat(row, column) {
      return this.selectDictLabel(this.sellStatusOptions, row.sellStatus);
    },
    // 最热状态：0未上架1已上架字典翻译
    courseHotFormat(row, column) {
      return this.selectDictLabel(this.hotStatusOptions, row.courseHot);
    },
    // 最新状态：0未上架1已上架字典翻译
    courseNewFormat(row, column) {
      return this.selectDictLabel(this.newStatusOptions, row.courseNew);
    },
    // 试看状态：0未上架1已上架字典翻译
    courseTryFormat(row, column) {
      return this.selectDictLabel(this.tryStatusOptions, row.courseTry);
    },
    //分类数据处理
    categoryFormat(row, column) {
      var datas = this.categoryOptions;
      var value = row.categoryId;
      var actions = [];
      Object.keys(datas).some((key) => {
        if (datas[key].categoryId == ('' + value)) {
          actions.push(datas[key].categoryName);
          return true;
        }
      })
      return actions.join('');
     // return this.selectDictLabel(data, row.categoryId);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        courseId: null,
        categoryId: null,
        courseName: null,
        chaptersNum: null,
        courseDescription: null,
        courseImgs: null,
        courseOldPrice: null,
        coursePrice: null,
        courseHot: null,
        courseNew: null,
        courseSales: null,
        courseTry: null,
        courseTryPages: null,
        courseTryTimes: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        auditStatus: 0,
        sellStatus: 0
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.courseId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加知识/课程";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const courseId = row.courseId || this.ids
      getCourse(courseId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改知识/课程";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.courseId != null) {
            updateCourse(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCourse(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const courseIds = row.courseId || this.ids;
      this.$confirm('是否确认删除知识/课程编号为"' + courseIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delCourse(courseIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有知识/课程数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportCourse(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },

    handleAvatarSuccess(res, file) {
      this.form.courseImgs = res.url;
    },
    // 上传预处理
    beforeUpload(file) {
      //this.uploadAction();
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
  }
};
</script>
